import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login, register, getUserInfo, updateUserInfo, uploadAvatar } from '@/api/user'
import { getUserStats } from '@/api/user'


export const useUserStore = defineStore('user', () => {
  const userInfo = ref({
    name: '',
    phone: '',
    email: '',
    city: '',
    gender: 'male',
    avatar: ''
  })
  const token = ref(localStorage.getItem('token') || '')
  
  const userStats = ref({
    favorites: 0,
    views: 0,
    contacts: 0,
    memberDays: 0
  })
  
  const isLoggedIn = computed(() => !!token.value)
  
  const getFullAvatarUrl = (avatarPath) => {
    if (!avatarPath) {
      console.log('头像路径为空，使用默认头像')
      return '/images/default-avatar.png'
    }
    
    console.log('处理头像路径:', avatarPath)
    
    // 如果已经是完整URL，直接返回
    if (avatarPath.startsWith('http') || avatarPath.startsWith('//') || avatarPath.startsWith('data:')) {
      return avatarPath
    }
    
    // 如果已经是绝对路径（以/开头），直接返回
    if (avatarPath.startsWith('/')) {
      return avatarPath
    }
    
    // 检查是否是 base64 图片
    if (avatarPath.startsWith('data:image')) {
      return avatarPath
    }
    
    // 对于数据库中的简单文件名，使用API服务（确保一致性）
    // 使用时间戳防止缓存
    const timestamp = Date.now()
    return `/api/avatar/${avatarPath}?t=${timestamp}`
  }

  // 计算属性：获取完整头像URL
  const avatarUrl = computed(() => {
    return getFullAvatarUrl(userInfo.value.avatar)
  })

  const extractFilename = (path) => {
    if (!path) return ''
    if (path.includes('/')) {
      const parts = path.split('/')
      return parts[parts.length - 1]
    }
    return path
  }
  const fetchUserStats = async () => {
    try {
      const response = await getUserStats()
      userStats.value = response.data.stats || {}
      console.log('获取用户统计信息成功:', userStats.value)
      return response
    } catch (error) {
      console.error('获取用户统计信息失败:', error)
      // 如果接口不存在，使用默认值
      userStats.value = {
        favorites: 0,
        views: 0,
        contacts: 0,
        memberDays: 0
      }
      throw error
    }
  }
  
  const loginUser = async (credentials) => {
    try {
      console.log('准备登录，数据:', credentials)
      const response = await login(credentials)
      
      if (response.data && response.data.token) {
        token.value = response.data.token
        const userData = response.data.user || {}
        userInfo.value = { 
          ...userInfo.value, 
          ...userData,
          avatar: extractFilename(userData.avatar) // 提取文件名
        }
        localStorage.setItem('token', token.value)
        console.log('登录成功:', userInfo.value)
        return response
      } else {
        throw new Error('登录响应中缺少token')
      }
    } catch (error) {
      console.error('登录失败:', error)
      if (error.response && error.response.status === 401) {
        logout()
      }
      throw error
    }
  }
  
  const registerUser = async (userData) => {
    try {
      console.log('准备注册，数据:', userData)
      const response = await register(userData)
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }
  
  const logout = () => {
    token.value = ''
    userInfo.value = {
      name: '',
      phone: '',
      email: '',
      city: '',
      gender: 'male',
      avatar: ''
    }
    userStats.value = {
      favorites: 0,
      views: 0,
      contacts: 0,
      memberDays: 0
    }
    localStorage.removeItem('token')
    console.log('已退出登录')
  }
  
  const fetchUserInfo = async () => {
    if (!token.value) {
      console.log('没有token，无法获取用户信息')
      throw new Error('未登录')
    }
    
    try {
      const response = await getUserInfo()
      const userData = response.data.user || {}
      userInfo.value = {
        name: '',
        phone: '',
        email: '',
        city: '',
        gender: 'male',
        avatar: '',
        ...userData,
        avatar: getFullAvatarUrl(userData.avatar) // 处理头像路径
      }
      console.log('获取用户信息成功:', userInfo.value)
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  const updateUser = async (userData) => {
    try {
      const response = await updateUserInfo(userData)
      const updatedUserData = response.data.user || {}
      userInfo.value = { 
        ...userInfo.value, 
        ...updatedUserData,
        avatar: getFullAvatarUrl(updatedUserData.avatar) // 处理头像路径
      }
      console.log('更新用户信息成功:', userInfo.value)
      return response
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  }

  const uploadUserAvatar = async (file) => {
    try {
      const response = await uploadAvatar(file)
      if (response.data && response.data.filename) {
        // 更新头像时使用完整URL
        const fullAvatarUrl = getFullAvatarUrl(response.data.filename)
        userInfo.value.avatar = fullAvatarUrl
        return response
      }
    } catch (error) {
      console.error('头像上传失败:', error)
      throw error
    }
  }
  
  return {
    userInfo,
    userStats,
    token,
    isLoggedIn,
    avatarUrl,
    loginUser,
    registerUser,
    logout,
    fetchUserInfo,
    updateUser,
    fetchUserStats,
    uploadUserAvatar,
    fetchUserStats 
  }
})